package de.kai_morich.simple_usb_terminal;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;

import cn.wch.ch37xdriver.CH37xDriver;

public class Main1Activity extends Activity {

	private static final String ACTION_USB_PERMISSION = "cn.wch.ch37xdriver.USB_PERMISSION";
	private boolean READ_ENABLE = false;
	private Handler handler;
	private EditText readText;
	private EditText writeText;
	private TextView DeviceInfo, DeviceState;
	private EditText DownCount, UpCount;
	private Button DownBtn, Up_ClearBtn, Down_ClearBtn, openButton;
	private boolean isOpen;
	private int Upload_count, Download_count;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_1main);

		initUI();

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 保持屏幕长亮状态
		MyApp.ch37xdrv = new CH37xDriver(
				(UsbManager) getSystemService(Context.USB_SERVICE),
				Main1Activity.this, ACTION_USB_PERMISSION);

		if (!MyApp.ch37xdrv.UsbFeatureSupported())// 判断系统是否支持USB HOST
		{
			Dialog dialog = new AlertDialog.Builder(Main1Activity.this)
					.setTitle("提示")
					.setMessage("您的手机不支持USB HOST，请更换其他手机。")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface arg0,
													int arg1) {
									System.exit(0);
								}
							}).create();
			dialog.setCanceledOnTouchOutside(false);
			dialog.show();
		}
		handler = new Handler() {//用于接收数据的handler
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				Upload_count += msg.what;
				byte[] recv = (byte[]) msg.obj;
                try {
                    String result = new String(recv, "UTF-8");
					readText.append(result);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
//				String append_String = recv.toString();
				String append_String = toHexString(recv, msg.what);

				UpCount.setText(String.valueOf(Upload_count));
			}
		};

		openButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!isOpen) {
					if (MyApp.ch37xdrv.OpenDevice()) {
						Toast.makeText(Main1Activity.this, "设备打开成功!",
								Toast.LENGTH_SHORT).show();
						isOpen = true;
						openButton.setText("关闭");
						READ_ENABLE = true;
						new ReadThread().start();
						DeviceInfo.setText("产品ID:"
								+ Integer.toHexString(MyApp.ch37xdrv.GetPID())
								+ ",设备ID:"
								+ Integer.toHexString(MyApp.ch37xdrv.GetVID()));
						DeviceState.setText("设备已打开");
						DownBtn.setEnabled(true);
					} else {
						Toast.makeText(Main1Activity.this, "设备打开失败!",
								Toast.LENGTH_SHORT).show();
					}

				} else {
					isOpen = false;
					READ_ENABLE = false;
					openButton.setText("打开");
					DeviceInfo.setText("设备未知");
					DeviceState.setText("设备已关闭");
					DownBtn.setEnabled(false);
					MyApp.ch37xdrv.CloseDevice();
				}
			}
		});
		// 发送按钮
		DownBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
//				byte[] send_buff;
				String input = ":RDMN00\r\n";
//				send_buff = toByteArray(":RDMN00\r\n");
				// 使用UTF-8编码将字符串转换为字节数组
                try {
                    byte[] send_buff = input.getBytes("UTF-8");
					int send_length = MyApp.ch37xdrv.WriteData(send_buff,
							send_buff.length);
					if (send_length < 0) {
						Toast.makeText(Main1Activity.this, "数据发送失败!",
								Toast.LENGTH_SHORT).show();
					} else {
						Download_count += send_length;
						DownCount.setText(String.valueOf(Download_count));
					}
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
//				send_buff = HexToByteArr(":RDMN000D0A");
//				send_buff = toByteArray("3A52444D4E30300D0A");
//				send_buff = new byte[]{(byte)0x3A, (byte)0x52, (byte)0x44, (byte)0x4D, (byte)0x4E, (byte)0x30,
//						(byte)0x30,  (byte)0x0D,(byte)0x0A};
//				send_buff = toByteArray(writeText.getText().toString());

			}
		});

	}
	public static byte[] hexStringToByteArray(String hexString) {
		// 1. 移除所有非十六进制字符（如冒号、空格等）
		String cleanHex = hexString.replaceAll("[^0-9a-fA-F]", "");

		// 2. 校验长度是否为偶数
		if (cleanHex.length() % 2 != 0) {
			throw new IllegalArgumentException("十六进制字符串长度必须为偶数");
		}

		// 3. 初始化字节数组
		byte[] byteArray = new byte[cleanHex.length() / 2];

		// 4. 每两个字符解析为一个字节
		for (int i = 0; i < byteArray.length; i++) {
			int index = i * 2;
			String byteStr = cleanHex.substring(index, index + 2);
			byteArray[i] = (byte) Integer.parseInt(byteStr, 16);
		}
		return byteArray;
	}
	public static byte[] HexToByteArr(String inHex) {//7E0101000104070D
		int hexlen = inHex.length();
		byte[] result;
		if (isOdd(hexlen) == 1) {
			++hexlen;
			result = new byte[hexlen / 2];
			inHex = "0" + inHex;
		} else {
			result = new byte[hexlen / 2];
		}

		int j = 0;

		for(int i = 0; i < hexlen; i += 2) {
			result[j] = HexToByte(inHex.substring(i, i + 2));
			++j;
		}

		return result;
	}
	public static int isOdd(int num) {
		return num & 1;
	}
	public static byte HexToByte(String inHex) {
		return (byte)Integer.parseInt(inHex, 16);
	}
	// 初始化控件
	public void initUI() {
		Upload_count = 0;
		Download_count = 0;
		isOpen = false;
		openButton = (Button) findViewById(R.id.OpenDevice);
		DownBtn = (Button) findViewById(R.id.DownBtn);
		Up_ClearBtn = (Button) findViewById(R.id.ClearBtn_Up);
		Down_ClearBtn = (Button) findViewById(R.id.ClearBtn_Down);

		DeviceInfo = (TextView) findViewById(R.id.DeviceInfo);
		DeviceState = (TextView) findViewById(R.id.DeviceState);
		DownCount = (EditText) findViewById(R.id.DownCount);
		UpCount = (EditText) findViewById(R.id.UpCount);
		readText = (EditText) findViewById(R.id.ReadValues);
		writeText = (EditText) findViewById(R.id.WriteValues);
		DownBtn.setEnabled(false);
		DeviceInfo.setText("产品ID:未知,设备ID:未知");
		DeviceState.setText("设备未打开");
		Up_ClearBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				readText.setText("");
				UpCount.setText("0");
				Upload_count = 0;
			}
		});

		Down_ClearBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				writeText.setText("");
				DownCount.setText("0");
				Download_count = 0;
			}
		});

	}

	// 读取线程：不断接收数据并通过消息发送到主线程
	private class ReadThread extends Thread {

		public void run() {

			while (READ_ENABLE) {
                try {
                    Thread.sleep(50); // 减少CPU占用
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Message msg = Message.obtain();
				int read_length;
				byte[] read_buff = new byte[64];
				if (MyApp.ch37xdrv != null) {
					read_length = MyApp.ch37xdrv.ReadData(read_buff, 64);
					if (read_length > 0) {
						msg.what = read_length;
						msg.obj = read_buff;
						handler.sendMessage(msg);
					}
				}
			}
		}
	}

	/**
	 * 将byte[]数组转化为String字符串
	 *
	 * @param arg    需要转换的byte[]数组
	 * @param length 需要转换的数组长度
	 * @return 转换后的String字符串
	 */
	private String toHexString(byte[] arg, int length) {
		String result = new String();
		if (arg != null) {
			for (int i = 0; i < length; i++) {
				result = result
						+ (Integer.toHexString(
						arg[i] < 0 ? arg[i] + 256 : arg[i]).length() == 1 ? "0"
						+ Integer.toHexString(arg[i] < 0 ? arg[i] + 256
						: arg[i])
						: Integer.toHexString(arg[i] < 0 ? arg[i] + 256
						: arg[i])) + " ";
			}
			return result;
		}
		return "";
	}

	/**
	 * 将String转化为byte[]数组
	 *
	 * @param arg 需要转换的String字符串
	 * @return 转换后的byte[]数组
	 */
	private byte[] toByteArray(String arg) {
		if (arg != null) {
			/* 1.去除String中的' '，然后将String转化为char数组 */
			char[] NewArray = new char[1000];
			char[] array = arg.toCharArray();
			int length = 0;
			for (int i = 0; i < array.length; i++) {
				if (array[i] != ' ') {
					NewArray[length] = array[i];
					length++;
				}
			}
			/* 将char数组中的值转成实际的十六进制数字 */
			int EvenLength = (length % 2 == 0) ? length : length + 1;
			if (EvenLength != 0) {
				int[] data = new int[EvenLength];
				data[EvenLength - 1] = 0;
				for (int i = 0; i < length; i++) {
					if (NewArray[i] >= '0' && NewArray[i] <= '9') {
						data[i] = NewArray[i] - '0';
					} else if (NewArray[i] >= 'a' && NewArray[i] <= 'f') {
						data[i] = NewArray[i] - 'a' + 10;
					} else if (NewArray[i] >= 'A' && NewArray[i] <= 'F') {
						data[i] = NewArray[i] - 'A' + 10;
					}
				}
				/* 将每两个char值组合成一个16进制数 */
				byte[] byteArray = new byte[EvenLength / 2];
				for (int i = 0; i < EvenLength / 2; i++) {
					byteArray[i] = (byte) (data[i * 2] * 16 + data[i * 2 + 1]);
				}
				return byteArray;
			}
		}
		return new byte[]{};
	}

}